package apportioner

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"

	// "bp/internal/service/entity/promotion"
	// "bp/internal/service/param"
	// "bp/internal/service/com/offer"
	"bp/internal/nsqserver/producer"
	"bp/internal/util"
	"context"
	"encoding/json"
	"time"
)

func (s *ApportionerComServiceImp) notifyOffApportionment(ctx context.Context, q *sqlc.Queries, offTransactionPtr *sqlc.OffTransaction, apportionmentOfDetailPtrs []*producer.ApportionmentOfOrderDetail) (err error) {
	transactionID := offTransactionPtr.ID

	// 这里使用独立的q
	topic := s.pub.GetPublishOffApportionmentsTopic()
	notificationPtr := &producer.OffApportionNotification{
		TransNo:     offTransactionPtr.OutTransNo,
		OrderNo:     offTransactionPtr.OutOrderNo,
		AfterSaleNo: offTransactionPtr.OutAfterSaleNo,
		Details:     apportionmentOfDetailPtrs,
		Timestamp:   time.Now().Unix(),
	}
	messageBytes, err := json.Marshal(notificationPtr)
	if err != nil {
		return
	}

	notifySn := util.Md5WithoutDash(messageBytes)

	err = s.entityHub.NsqService.UpsertNsqPub(ctx, q, topic, notifySn, messageBytes)
	if err != nil {
		return
	}

	// err = s.pub.PublishNotification(nsqPubPtr)
	// if err != nil {
	// 	return
	// }
	s.slog.Infof("交易(%d)的优惠分摊消息生成 ok", transactionID)
	err = s.entityHub.OffTransactionService.MarkOffTransactionApportionmentsSended(ctx, q, transactionID)
	if err != nil {
		return
	}

	s.slog.Infof("交易(%d)的标记分摊记录已进入发送队列 ok", transactionID)
	return
}
